package com.icesoft.base.manager.service.manager;

import com.icesoft.base.manager.entity.manager.RelSysOrgOwner;
import com.icesoft.core.dao.base.BaseDao;
import com.icesoft.core.dao.criteria.QueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RelSysOrgOwnerService extends BaseDao<RelSysOrgOwner> {

    public void deleteOrgRelation(int orgId) {
        delete(QueryBuilder.get("orgId", orgId).orEq("ownerOrgId", orgId));
    }

    @Transactional
    public void updateOwnerOrg(int orgId, List<Integer> ownerOrgIds) {
        List<RelSysOrgOwner> list = findByOrgId(orgId);
        List<RelSysOrgOwner> deleteList = new ArrayList<>();
        for (RelSysOrgOwner relSysOrgOwner : list) {
            if (ownerOrgIds.contains(relSysOrgOwner.getOwnerOrgId())) {// 包含表示一致，不用处理
                ownerOrgIds.remove(new Integer(relSysOrgOwner.getOwnerOrgId()));
            } else {
                deleteList.add(relSysOrgOwner);// 不包含，需要删除
            }
        }
        delete(deleteList);
        for (int orgOwnerId : ownerOrgIds) {
            RelSysOrgOwner relSysOrgOwner = new RelSysOrgOwner();
            relSysOrgOwner.setOrgId(orgId);
            relSysOrgOwner.setOwnerOrgId(orgOwnerId);
            create(relSysOrgOwner);
        }
    }

    public List<RelSysOrgOwner> findByOrgId(int orgId) {
        return find(QueryBuilder.get("orgId", orgId));
    }

    public List<Integer> findOwnerOrgIdsByOrgId(int orgId) {
        List<Integer> ids = new ArrayList<>();
        if (orgId == 0) {
            return ids;
        }
        List<RelSysOrgOwner> list = findByOrgId(orgId);
        return list.stream().map(RelSysOrgOwner::getOwnerOrgId).collect(Collectors.toList());
    }
}
